package com.sgb.kjwl.view.ui.fragment.transport;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.motion.widget.MotionLayout;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.fondesa.recyclerviewdivider.DividerDecoration;
import com.google.android.material.tabs.TabLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentMapCarsBinding;
import com.sgb.kjwl.model.entity.transport.FilterTabEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.transport.GoodsSourceLocationEntity;
import com.sgb.kjwl.model.entity.transport.SingleItemConstant;
import com.sgb.kjwl.model.entity.transport.VehicleHallMapEntity;
import com.sgb.kjwl.utils.ChineseEnglishAndNumberFilter;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.TextViewUtils;
import com.sgb.kjwl.utils.TouchHelper;
import com.swgk.core.util.UiUtil;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.vehicleManagement.VehicleDetailActivity;
import com.sgb.kjwl.view.ui.adapter.home.CarsHallListAndMapAdapter;
import com.sgb.kjwl.view.ui.adapter.transport.LogisticsFilterTabAdapter;
import com.sgb.kjwl.view.widget.CarMapInfoWindow;
import com.sgb.kjwl.view.widget.CarTypePicPopWindow;
import com.sgb.kjwl.view.widget.GoodsTypePopWindow3;
import com.sgb.kjwl.view.widget.LoadingTimePopWindow;
import com.sgb.kjwl.view.widget.MapHallCarPopWindow;
import com.sgb.kjwl.view.widget.ThreeLevelAreaWindow;
import com.sgb.kjwl.viewmodel.transport.MapCarsFramgentModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.util.ClickUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.PermissionUtils;
import com.swgk.core.util.ScreenUtil;
import com.swgk.core.util.SharedPreferenceUtil;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author: 杨畔
 * @date: 3/11/21 5:30 PM
 * @Description: 地图找车
 */
public class MapCarsFragment extends AppLazyFragment implements
        TabLayout.OnTabSelectedListener, AMap.OnMarkerClickListener,
        AMap.OnCameraChangeListener,
        AMap.OnMapTouchListener {
    MapCarsFramgentModel viewModel;
    FragmentMapCarsBinding binding;
    //
    private Activity _mActivity;
    //筛选栏
    private final int TAB_CAR_LOCATION = 0;
    //    private final int TAB_CAR_TYPE = 1;   2.1.9.1 暂时去掉车型图筛选功能
    private final int TAB_CAR_LENGTH = 1;
    private final int TAB_CAR_FEATURE = 2;
    private final int TAB_CAR_DATE = 3;
    private static final String CAN_SHOW_LISTVIEW = "CAN_SHOW_LISTVIEW";
    private List<FilterTabEntity> mFilterList;
    private LogisticsFilterTabAdapter mFilterAdapter;
    //地图控制器
    private AMap aMap;
    //当前定位位置信息
    private LatLng mCurLatLng;
    //地图缩放比例
    private float mZoom = 11;
    //最小缩放级别（全国）
    private final float mMinZoom = 3;
    //全国中心点经纬度
    private final LatLng mCenterLatLng = new LatLng(35.03349, 103.03319);
    //页面弹窗
    private GoodsTypePopWindow3 mTypePop;//车型
    private ThreeLevelAreaWindow mSendPop;//车辆位置
    private CarTypePicPopWindow mTypePicPop;//车型图
    private GoodsTypePopWindow3 mLenPop;//车长
    private GoodsTypePopWindow3 mFeaturePop;//功能
    private LoadingTimePopWindow mLoadingTimePop;//装车时间
    private MapHallCarPopWindow mMapCarPop;//地图车辆弹窗
    //列表数据
    private int mPage = 1;
    private List<VehicleHallMapEntity> mList;
    private CarsHallListAndMapAdapter mAdapter;
    //marker集合
    private final List<Marker> mMarkers = new ArrayList<>();
    //当前最后一个点击的marker
    private Marker mLastMarker;
    //跳转回来清空页面消息标识
    public boolean mIsNeedClearMsg;
    public boolean canShowListView;
    //屏幕宽度
    private int mScreenWidth;
    //是否需要移动地图加载数据
    private boolean mIsNeedLoadByCamera = true;

    //当前是否是搜索行为
    private boolean currentIsSearching = false;
    private boolean mapShowing = false;
    //初始车辆no
    private String mInitCarTypeNo;
    //是否是初次加载
    private boolean mIsInit;
    //是否是展开的筛选栏，默认展开
    private boolean mIsExpand = true;
    //手势监听帮助类
    private TouchHelper mTouchHelper;
    //搜索时是否移动位置
    boolean isCameraToPosition;
    //第一加载
    boolean mFirstLoad = true;


    //地图上的车辆数据集合(新请求下来的数据需要对比去重)
    private Map<String, VehicleHallMapEntity> carEntities = new HashMap<>();

    public static MapCarsFragment newInstance(boolean canShowListView) {
        return newInstance(canShowListView, "");
    }

    public static MapCarsFragment newInstance(boolean canShowListView, String no) {
        MapCarsFragment fragment = new MapCarsFragment();
        Bundle args = new Bundle();
        args.putBoolean(CAN_SHOW_LISTVIEW, canShowListView);
        args.putString(RouterKey.NO, no);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        _mActivity = (Activity) context;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            canShowListView = getArguments().getBoolean(CAN_SHOW_LISTVIEW, true);
            mInitCarTypeNo = getArguments().getString(RouterKey.NO);
        }
        if (!TextUtils.isEmpty(mInitCarTypeNo)) {
            mIsInit = true;
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_map_cars, container, false);
        binding.setLifecycleOwner(this);
        binding.mapFindCarByMap.onCreate(savedInstanceState);
        viewModel = new ViewModelProvider(this).get(MapCarsFramgentModel.class);
        return binding.getRoot();
    }

    @Override
    protected void onLazyLoad() {
        //先加载loading
        DialogHelper.showProgressDialog(getContext(), null, "数据加载中...", 0, false, null).setCanceledOnTouchOutside(true);
        initSwitch();
        initMap();
        initRecycler();
        initPopup();
        initEvent();
        initData();
    }

    private void initSwitch() {
        binding.cardFindCarByMapSwitch.setVisibility(canShowListView ? View.VISIBLE : View.GONE);
        binding.listDataLayout.setVisibility(canShowListView ? View.VISIBLE : View.GONE);
        mapShowing = !canShowListView;
//        binding.flExpand.setVisibility(mapShowing ? View.VISIBLE : View.GONE);
    }

    /**
     * 初始化地图
     */
    private void initMap() {
        //获取地图控制类
        aMap = binding.mapFindCarByMap.getMap();
        //显示定位蓝点
        aMap.getUiSettings().setMyLocationButtonEnabled(false);
        //显示缩放控制器
        aMap.getUiSettings().setZoomControlsEnabled(false);
        //设置弹窗样式
        aMap.setInfoWindowAdapter(new CarMapInfoWindow(_mActivity));
        //marker点击监听
        aMap.setOnMarkerClickListener(this);
        //监听地图移动
        aMap.setOnCameraChangeListener(this);
        //地图手势监听
        aMap.setOnMapTouchListener(this);
    }

    private void initRecycler() {
        //筛选栏
        mFilterList = new ArrayList<>();
        viewModel.initFilterTab(mFilterList);
        mFilterAdapter = new LogisticsFilterTabAdapter(mFilterList);
        binding.rvFindCarByMapFilter.setNestedScrollingEnabled(false);
        binding.rvFindCarByMapFilter.setLayoutManager(new LinearLayoutManager(_mActivity, RecyclerView.HORIZONTAL, false));
        DividerDecoration.builder(_mActivity)
                .color(Color.TRANSPARENT)
                .size(10, TypedValue.COMPLEX_UNIT_DIP)
                .build()
                .addTo(binding.rvFindCarByMapFilter);
        mFilterAdapter.bindToRecyclerView(binding.rvFindCarByMapFilter);
        //车辆列表
        mList = new ArrayList<>();
        mAdapter = new CarsHallListAndMapAdapter(mList);
        binding.rvFindCarByMapCar.setLayoutManager(new LinearLayoutManager(_mActivity));
//        binding.rvFindCarByMapCar.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0,
//                _mActivity.getResources().getDimension(R.dimen.dp5),
//                Color.TRANSPARENT));
        mAdapter.bindToRecyclerView(binding.rvFindCarByMapCar);

        binding.rvFindCarByMapCar.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (mIsExpand && dy > 30) {
                    binding.mlFilterRoot.transitionToEnd();
                }
            }
        });
    }

    private void initPopup() {
        mFilterAdapter.setTabStatus(TAB_CAR_LOCATION, LogisticsFilterTabAdapter.SELECTED);
        //发货地
        mSendPop = new ThreeLevelAreaWindow(_mActivity) {
            @Override
            protected void resultContent(String name, String simpleName) {
                mFilterAdapter.setTabTitle(TAB_CAR_LOCATION, DefaultUtil.getMaxLengthText(simpleName, 4));
            }
        };
        mSendPop.setAreaSingle();
        mSendPop.setCitySingle();
        mSendPop.setProvinceSingle();
        mSendPop.setShowSimpleName(true);
        mSendPop.setAllSingleSelect(true);
        mSendPop.setOnlyShowProAndCity(true);
        mSendPop.setShowOnlyAreaNoData(true);
        mSendPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                viewModel.ldFilter.getValue().setSend(entity);
                if ("不限".equals(entity.getProvinceName())) {
                    if (mapShowing) {
                        //地图缩小展示全中国
                        mZoom = mMinZoom;
//                        mIsNeedLoadByCamera = true;
                        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
                    } else {
                        refreshData();
                    }
                } else {
                    viewModel.getLocation(_mActivity, entity.getCityName(), DefaultUtil.getString(entity.getAreaName()));
                }
            }
        });
        mSendPop.setOnDismissListener(() -> {
            mFilterAdapter.setTabStatus(TAB_CAR_LOCATION, LogisticsFilterTabAdapter.SELECTED);
        });
        //车长
        mLenPop = new GoodsTypePopWindow3(_mActivity);
        mLenPop.setOnResultClick((key1, key2, key3) -> {
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            mFilterAdapter.setTabTitle(TAB_CAR_LENGTH, entity.getName());
            viewModel.ldFilter.getValue().setCarLen(entity);
            //刷新
            refreshData();
        });
        mLenPop.setOnDismissListener(() -> {
            if ("车长".equals(mFilterList.get(TAB_CAR_LENGTH).getTitle())) {
                mFilterAdapter.setTabStatus(TAB_CAR_LENGTH, LogisticsFilterTabAdapter.NORMAL);
            } else {
                mFilterAdapter.setTabStatus(TAB_CAR_LENGTH, LogisticsFilterTabAdapter.SELECTED);
            }
        });
        //车辆类型
        mTypePop = new GoodsTypePopWindow3(_mActivity);
        mTypePop.setOnResultClick((key1, key2, key3) -> {
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            viewModel.ldFilter.getValue().setCarType(entity);
            binding.tlFindCarByMap.selectTab(binding.tlFindCarByMap.getTabAt((Integer) key2));
            //根据车型筛选数据
            filterByCarType();
        });
        mTypePop.setOnDismissListener(() -> {
            binding.ivFindCarByMapEdit.setImageResource(R.mipmap.btn_expand1);
        });
        //车型图       2.1.9.1 去掉车型图
//        mTypePicPop = new CarTypePicPopWindow(_mActivity);
//        mTypePicPop.setOnDismissListener(() -> {
//            mFilterAdapter.setTabStatus(TAB_CAR_TYPE, LogisticsFilterTabAdapter.NORMAL);
//        });
        //功能
        mFeaturePop = new GoodsTypePopWindow3(_mActivity);
        mFeaturePop.setOnResultClick((key1, key2, key3) -> {
            GoodsInfoTypeEntity3 entity = (GoodsInfoTypeEntity3) key1;
            mFilterAdapter.setTabTitle(TAB_CAR_FEATURE, entity.getName());
            viewModel.ldFilter.getValue().setCarFunction(entity);
            //刷新
            refreshData();
        });
        mFeaturePop.setOnDismissListener(() -> {
            if ("功能".equals(mFilterList.get(TAB_CAR_FEATURE).getTitle())) {
                mFilterAdapter.setTabStatus(TAB_CAR_FEATURE, LogisticsFilterTabAdapter.NORMAL);
            } else {
                mFilterAdapter.setTabStatus(TAB_CAR_FEATURE, LogisticsFilterTabAdapter.SELECTED);
            }
        });
        //装车时间
        mLoadingTimePop = new LoadingTimePopWindow(_mActivity);
        mLoadingTimePop.setOnResultClick((key1, key2, key3) -> {
            long startTime = (long) key1;
            long endTime = (long) key2;
            viewModel.ldFilter.getValue().setShipmentTime(startTime);
            viewModel.ldFilter.getValue().setShipmentEndTime(endTime);
            if (startTime != 0 && endTime != 0) {//要求回显
                mFilterAdapter.setTabTitle(TAB_CAR_DATE, UiUtil.get2Time(startTime) + "-" + UiUtil.get2Time(endTime));
            } else if (startTime != 0) {
                mFilterAdapter.setTabTitle(TAB_CAR_DATE, UiUtil.get2Time(startTime));
            } else if (endTime != 0) {
                mFilterAdapter.setTabTitle(TAB_CAR_DATE, UiUtil.get2Time(endTime));
            }
            //刷新
            refreshData();

        });
        mLoadingTimePop.setOnDismissListener(() -> {
            if (viewModel.ldFilter.getValue().getShipmentTime() != 0
                    || viewModel.ldFilter.getValue().getShipmentEndTime() != 0) {
                mFilterAdapter.setTabStatus(TAB_CAR_DATE, LogisticsFilterTabAdapter.SELECTED);
            } else {
                mFilterAdapter.setTabStatus(TAB_CAR_DATE, LogisticsFilterTabAdapter.NORMAL);
            }
        });
        //地图车辆弹窗
        mMapCarPop = new MapHallCarPopWindow(_mActivity);
        mMapCarPop.setOnResultCallBack(result -> mIsNeedClearMsg = true);
        mMapCarPop.setOnDismissListener(this::resetOtherMarker);
        mMapCarPop.setOnClickCallBack(account -> {
                    // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
                    buildSingleTalking(account);
                }
        );
    }

    private void initEvent() {
        binding.setOnClick(this);
        binding.etFindCarByMapSearch.setFilters(new InputFilter[]{new ChineseEnglishAndNumberFilter()});
        //注册im消息监听
//        NIMClient.getService(MsgServiceObserve.class).observeRecentContact(this, true);
        //筛选点击
        mFilterAdapter.setOnItemClickListener((adapter, view, position) -> {
            switch (position) {
                case TAB_CAR_LOCATION://车辆位置
                    if (viewModel.ldAddress.getValue() != null) {
                        mFilterAdapter.setTabStatus(TAB_CAR_LOCATION, LogisticsFilterTabAdapter.EXPAND);
                        showPopup(mSendPop);
                    }
                    break;
//                case TAB_CAR_TYPE://车型图
//                    if (viewModel.ldCarType.getValue() != null) {
//                        mFilterAdapter.setTabStatus(TAB_CAR_TYPE, LogisticsFilterTabAdapter.EXPAND);
//                        showPopup(mTypePicPop);
//                    }
//                    break;
                case TAB_CAR_LENGTH://车长
                    if (viewModel.ldCarLen.getValue() != null) {
                        mFilterAdapter.setTabStatus(TAB_CAR_LENGTH, LogisticsFilterTabAdapter.EXPAND);
                        showPopup(mLenPop);
                    }
                    break;
                case TAB_CAR_FEATURE://功能
                    if (viewModel.ldCarFunction.getValue() != null) {
                        mFilterAdapter.setTabStatus(TAB_CAR_FEATURE, LogisticsFilterTabAdapter.EXPAND);
                        showPopup(mFeaturePop);
                    }
                    break;
                case TAB_CAR_DATE://装车时间
                    mFilterAdapter.setTabStatus(TAB_CAR_DATE, LogisticsFilterTabAdapter.EXPAND);
                    showPopup(mLoadingTimePop);
                    break;
            }
        });
        binding.srlFindCarByMapRefresh.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                mPage = mPage + 1;
                refreshDataByPage(mPage);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                refreshData();
            }
        });
        mAdapter.setOnItemClickListener((adapter, view, position) -> {
            VehicleHallMapEntity entity = mList.get(position);
            if (entity.getItemType() == SingleItemConstant.TYPE_ONE) {
                //跳转车辆详情
                VehicleDetailActivity.start(_mActivity, entity.getDriverAuthNo());
            }
        });
//        binding.rvFindCarByMapCar.addOnScrollListener(new RecyclerView.OnScrollListener() {
//            //滑动开始下标，默认为0
//            private int startPosition;
//
//            @Override
//            public void onScrollStateChanged(@NonNull @NotNull RecyclerView recyclerView, int newState) {
//                super.onScrollStateChanged(recyclerView, newState);
//                LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
//                if (manager == null) return;
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    //获取滑动结束位置
//                    int endPosition = manager.findFirstVisibleItemPosition();
//                    //刷新重置开始位置
//                    if (endPosition == 0) {
//                        startPosition = endPosition;
//                    }
//                    //判断结束位置是否滑动超过一个item
//                    if (mIsExpand && endPosition - startPosition > 1) {
//                        binding.mlFilterRoot.transitionToEnd();
//                        startPosition = endPosition;
//                    }
//                }
//            }
//
//            @Override
//            public void onScrolled(@NonNull @NotNull RecyclerView recyclerView, int dx, int dy) {
//                super.onScrolled(recyclerView, dx, dy);
//            }
//        });
        //车辆类型数据
        viewModel.ldCarType.observe(this, list -> {
            mTypePop.setData(list, 0);
//            mTypePicPop.setData(list);
            //添加tab
            int index = 0;
            for (GoodsInfoTypeEntity3 entity3 : list) {
                binding.tlFindCarByMap.addTab(binding.tlFindCarByMap.newTab().setText(entity3.getName()));
                if (!TextUtils.isEmpty(mInitCarTypeNo) && mInitCarTypeNo.equals(entity3.getNo())) {
                    index = list.indexOf(entity3);
                }
            }
            //车辆类型选中监听
            binding.tlFindCarByMap.addOnTabSelectedListener(this);
            //判断是否有默认选中类型
            int finalIndex = index;
            binding.tlFindCarByMap.postDelayed(() -> binding.tlFindCarByMap.selectTab(binding.tlFindCarByMap.getTabAt(finalIndex)), 100);

        });
        //车辆长度数据
        viewModel.ldCarLen.observe(this, list -> {
            mLenPop.setData(VehicleConstant.sortCarLength(list), 0);
        });
        //车辆功能数据
        viewModel.ldCarFunction.observe(this, list -> mFeaturePop.setData(list, 0));
        //省市区监听
        viewModel.ldAddress.observe(this, addressEntities -> {
            if (mCurLatLng == null) {
                GoodsSourceLocationEntity entity = viewModel.ldFilter.getValue().getSend();
                //通过城市定位
                viewModel.getLocation(_mActivity, entity.getCityName(), DefaultUtil.getString(entity.getAreaName()));
            } else {
                mZoom = 11;
                cameraToPosition(mCurLatLng.latitude, mCurLatLng.longitude);
            }
        });
        //查找地区下标监听
        viewModel.ldPosition.observe(this, positionEntity -> {
            GoodsSourceLocationEntity entity = viewModel.ldFilter.getValue().getSend();
            mSendPop.setDataAndPosition(viewModel.ldAddress.getValue(), entity.getProvinceName(), entity.getCityName(), "");
            //设置车辆位置
            String locationText;
            if (!TextUtils.isEmpty(entity.getCityName())) {
                if ("不限".equals(entity.getCityName())) {
                    locationText = "不限".equals(entity.getProvinceName()) ? "全国" : entity.getProvinceName();
                } else {
                    locationText = entity.getCityName();
                }
            } else {
                locationText = "不限".equals(entity.getProvinceName()) ? "全国" : entity.getProvinceName();
            }
            mFilterAdapter.setTabTitle(TAB_CAR_LOCATION, DefaultUtil.getMaxLengthText(locationText, 4));

            requestData();

//            if (mapShowing) {
//                viewModel.getCarToMap(getSearchText());
//                //从其他城市搜索滑动到定位位置
//                if (isCameraToPosition) {
//                    isCameraToPosition = false;
//                    if (PermissionUtils.checkPermission(_mActivity, Manifest.permission.ACCESS_FINE_LOCATION)) {
//                        double lat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
//                        double log = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
//                        cameraToPosition(lat, log);
//                    } else {
//                        viewModel.getLocation(_mActivity, entity.getCityName(), DefaultUtil.getString(entity.getAreaName()));
//                    }
//                }
//            } else {
//                viewModel.getCarToList(mPage, getSearchText());
//            }
        });
        //根据省市区查找经纬度监听
        viewModel.ldLatLng.observe(this, latLng -> {
            if (latLng != null) {
                mZoom = 11;
                cameraToPosition(latLng.latitude, latLng.longitude);
                refreshData();
            }
        });
        //筛选栏动画监听
        binding.mlFilterRoot.setTransitionListener(new MotionLayout.TransitionListener() {
            @Override
            public void onTransitionStarted(MotionLayout motionLayout, int i, int i1) {

            }

            @Override
            public void onTransitionChange(MotionLayout motionLayout, int i, int i1, float v) {

            }

            @Override
            public void onTransitionCompleted(MotionLayout motionLayout, int i) {
                mIsExpand = binding.mlFilterRoot.getProgress() == 0.0f;
                if (mIsExpand) {
                    binding.tvExpand.setText("收起筛选条件");
                    TextViewUtils.changeTextView(_mActivity, binding.tvExpand, R.drawable.btn_shop_up, false);
                } else {
                    binding.tvExpand.setText("更多筛选条件");
                    TextViewUtils.changeTextView(_mActivity, binding.tvExpand, R.drawable.btn_shop_down, false);
                }
            }

            @Override
            public void onTransitionTrigger(MotionLayout motionLayout, int i, boolean b, float v) {
            }
        });
        //地图找车数据
        viewModel.ldCars.observe(this, this::syncData);
    }

    private void initData() {
        //设置城市
        if (PermissionUtils.checkPermission(_mActivity, Manifest.permission.ACCESS_FINE_LOCATION)) {
            //设置经纬度
            double lat = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LATITUDE_ID, "0"));
            double log = NumberUtil.convertToDouble(SharedPreferenceUtil.getInstance().getString(SharedPreferenceUtil.LONGITUDE_ID, "0"));
            if (lat != 0 && log != 0) {
                //设置定位信息
                mCurLatLng = new LatLng(lat, log);
                viewModel.ldFilter.getValue().setLatitude(mCurLatLng.latitude);
                viewModel.ldFilter.getValue().setLongitude(mCurLatLng.longitude);
            }
        } else {
            mFilterAdapter.setTabTitle(TAB_CAR_LOCATION, DefaultUtil.getMaxLengthText("乌鲁木齐", 4));
        }
        //获取数据
        viewModel.getAddressModel(_mActivity);
        viewModel.getCarFunction();
    }

    /**
     * 刷新数据
     * （下拉加载或者改变筛选条件）
     */
    private void refreshData() {
        refreshDataByPage(1);
    }

    /**
     * 请求数据（不刷新）
     */
    private void requestData() {
        if (mapShowing) {
            viewModel.getCarToMap(getSearchText());
        } else {
            viewModel.getCarToList(mPage, getSearchText());
        }
    }

    private void refreshDataByPage(int page) {
        this.mPage = page;
        if (mapShowing) {
            if (mPage <= 1) {
                clearMarker();
            }
            viewModel.getCarToMap(getSearchText());
        } else {
            viewModel.getCarToList(mPage, getSearchText());
        }
    }


    /**
     * 清除页面marker
     */
    private void clearMarker() {
        if (aMap != null)
            aMap.clear();
        if (mMarkers != null)
            mMarkers.clear();
        if (carEntities != null)
            carEntities.clear();
    }

    /**
     * 刷新地图覆盖物
     */
    private void refreshMapMarker(List<VehicleHallMapEntity> list) {
        cameraToPosition(viewModel.ldFilter.getValue().getLatitude(), viewModel.ldFilter.getValue().getLongitude());
        if (list == null || list.size() == 0) return;

        for (VehicleHallMapEntity entity : list) {
            if (entity.getLatitude() == null) {
                return;
            }
            if (!TextUtils.isEmpty(entity.getNo())) {
                if (carEntities == null)
                    carEntities = new HashMap<>();
                if (carEntities.size() > 0) {
                    if (!carEntities.keySet().contains(entity.getNo())) {
                        carEntities.put(entity.getNo(), entity);
                        addMarker(entity);
                    }
                } else {
                    carEntities.put(entity.getNo(), entity);
                    addMarker(entity);
                }
            }
        }
    }

    /**
     * 添加覆盖物
     */
    private void addMarker(VehicleHallMapEntity entity) {
        if (entity == null || entity.getLongitude() == null || entity.getLatitude() == null)
            return;
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(new LatLng(entity.getLatitude().doubleValue(), entity.getLongitude().doubleValue()));
        markerOption.icon(BitmapDescriptorFactory.fromResource(entity.getIsCarrierBusiness() == 1
                ? R.mipmap.ic_find_car_marker_yellow
                : R.mipmap.ic_find_car_marker_red));
        Marker marker = aMap.addMarker(markerOption);
        //设置附着对象
        marker.setObject(entity);
        mMarkers.add(marker);
    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        if (viewModel.ldCarType.getValue() != null && tab.getPosition() < viewModel.ldCarType.getValue().size()) {
            mTypePop.setDefItem(tab.getPosition());
            //请求数据
            viewModel.ldFilter.getValue().setCarType(viewModel.ldCarType.getValue().get(tab.getPosition()));
            //根据车型筛选数据
            filterByCarType();
        }
    }

    /**
     * 根据车型筛选数据
     */
    private void filterByCarType() {
        //筛选车长类型时删除所有标注点
        clearMarker();
        //切换车型时重置车长，填充车长筛选数据
        viewModel.ldFilter.getValue().setCarLen(null);
        //刷新车长数据
        if (viewModel.ldFilter.getValue() != null && viewModel.ldFilter.getValue().getCarType() != null) {
            viewModel.ldCarLen.postValue(viewModel.ldFilter.getValue().getCarType().getCarLenList());
        }
        mFilterAdapter.setTabStatusAndTitle(TAB_CAR_LENGTH, LogisticsFilterTabAdapter.NORMAL, "车长");
        //刷新
        refreshData();
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {
        //不用实现
    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {
        //不用实现
    }

    /**
     * 根据经纬度移动地图，标记中心点
     */
    private void cameraToPosition(Double lat, Double lng) {
        if (aMap == null || lat == 0 || lng == 0) return;
        //切换地图中心点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), mZoom));
        viewModel.ldFilter.getValue().setLatitude(lat);
        viewModel.ldFilter.getValue().setLongitude(lng);
    }

    @Override
    public void onCameraChange(CameraPosition cameraPosition) {
        //不用实现
    }

    /**
     * 地图移动完毕
     */
    @Override
    public void onCameraChangeFinish(CameraPosition cameraPosition) {
        //设置定位信息
        mCurLatLng = cameraPosition.target;
        viewModel.ldFilter.getValue().setLatitude(mCurLatLng.latitude);
        viewModel.ldFilter.getValue().setLongitude(mCurLatLng.longitude);
        //设置当前搜索半径(以屏幕宽度为直径)
        setCurrentRadius();
        //比较缩放比例
        if (viewModel.ldFilter.getValue().getZoom() != cameraPosition.zoom) {
            viewModel.ldFilter.getValue().setZoom(cameraPosition.zoom);
            return;
        }
        //初次加载会在车型接口获取后刷新数据，此处返回
        if (mIsInit) {
            mIsInit = false;
            return;
        }
        if (mapShowing && mIsNeedLoadByCamera && !mFirstLoad) {
            viewModel.getCityByLocation(getActivity(), mCurLatLng.latitude, mCurLatLng.longitude);
        } else {
            mFirstLoad = false;
        }
    }

    /**
     * 地图手势监听
     */
    @Override
    public void onTouch(MotionEvent motionEvent) {
        if (mTouchHelper == null) {
            mTouchHelper = TouchHelper.newInstance().addTouchListener(new TouchHelper.TouchListenerProxy() {
                @Override
                public void handlerUpTouch(float downX, float downY, float upX, float upY) {
                    //纵向滑动距离小于-100px
                    if (mIsExpand && upY - downY < -100) {
                        binding.mlFilterRoot.transitionToEnd();
                    }
                }
            });
        }
        mTouchHelper.onTouch(null, motionEvent);
    }

    /**
     * 设置当前半径
     */
    private void setCurrentRadius() {
        if (mScreenWidth == 0) {
            mScreenWidth = ScreenUtil.getDisplayWidth();
        }
        //屏幕宽度的一半 * 当前缩放1px代表的米数
        String radius = NumberUtil.trim0(mScreenWidth / 2f * aMap.getScalePerPixel());
        //设置半径
        viewModel.ldFilter.getValue().setRadius(radius);
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        VehicleHallMapEntity entity = (VehicleHallMapEntity) marker.getObject();
        marker.hideInfoWindow();
        marker.setIcon(BitmapDescriptorFactory.fromResource(entity.getIsCarrierBusiness() == 1
                ? R.mipmap.ic_find_car_marker_yellow_click
                : R.mipmap.ic_find_car_marker_red_click));
        mLastMarker = marker;
        //显示弹窗
        mMapCarPop.showPopwindowBottom(binding.mapFindCarByMap);
        mMapCarPop.setData(entity);
        return true;
    }

    /**
     * 还原其他marker
     */
    private void resetOtherMarker() {
        if (mLastMarker != null) {
            VehicleHallMapEntity entity = (VehicleHallMapEntity) mLastMarker.getObject();
            if (entity == null) {
                mLastMarker = null;
                return;
            }
            mLastMarker.setIcon(BitmapDescriptorFactory.fromResource(entity.getIsCarrierBusiness() == 1
                    ? R.mipmap.ic_find_car_marker_yellow
                    : R.mipmap.ic_find_car_marker_red));
//            }
            mLastMarker = null;
        }
    }

    /**
     * 清除消息提醒
     */
    public void clearMsgTip(Object result) {
        if (!mIsNeedClearMsg) return;
        mIsNeedClearMsg = false;
        //跳转页面后返回则清空消息提醒
        if (mMarkers.size() == 0) return;
        //清空所有消息提醒
        for (Marker marker : mMarkers) {
            VehicleHallMapEntity entity = (VehicleHallMapEntity) marker.getObject();
            //跳过无消息marker
//            if (entity.getImContact() == null) continue;
            //置空新消息
//            entity.setImContact(null);
            //跳过当前选中marker
            if (mLastMarker != null && marker.getObject() == mLastMarker.getObject()) continue;
            marker.hideInfoWindow();
            marker.setIcon(BitmapDescriptorFactory.fromResource(entity.getIsCarrierBusiness() == 1
                    ? R.mipmap.ic_find_car_marker_yellow
                    : R.mipmap.ic_find_car_marker_red));
        }
    }

    public void syncData(List<VehicleHallMapEntity> entity) {
        if (mapShowing) {
            refreshMapMarker(entity);
        } else {
            syncDataList(entity);
        }
    }

    public void syncDataList(List<VehicleHallMapEntity> entity) {
        binding.srlFindCarByMapRefresh.finishRefresh();
        binding.srlFindCarByMapRefresh.finishLoadMore();
        if (mPage == 1) {
            mList.clear();
        }
        if (entity != null) {
            mList.addAll(entity);
        }
        mAdapter.notifyDataSetChanged();
        //判断列表是否为null
        if (mList.size() == 0) {
            /*     binding.srlFindCarByMapRefresh.setVisibility(View.GONE);*/
            binding.emptyStateView.setVisibility(View.VISIBLE);
        } else {
            /* binding.srlFindCarByMapRefresh.setVisibility(View.VISIBLE);*/
            binding.emptyStateView.setVisibility(View.GONE);
        }
        //
        if (entity.size() >= viewModel.limit) {
            binding.srlFindCarByMapRefresh.resetNoMoreData();
        } else {
            binding.srlFindCarByMapRefresh.finishLoadMoreWithNoMoreData();
        }
    }

    @Override
    public void onClick(View v) {
        if (ClickUtils.isDoubleClick()) {
            return;
        }
        if (v == binding.ivFindCarByMapEdit) {
            if (viewModel.ldCarType.getValue() != null) {
                binding.ivFindCarByMapEdit.setImageResource(R.mipmap.btn_expand_up_gray);
                mTypePop.showPopwindow(binding.llFindCarByMapCategory, 0, 0);
            }
        } else if (v == binding.tvFindCarByMapLoad) {
            //加载车辆，手动点击时清空省市区no
            viewModel.ldFilter.getValue().setSend(new GoodsSourceLocationEntity());
            refreshData();
            //暂时不刷新当前定位点地区信息
//            viewModel.getCityByLocation(_mActivity, mCurLatLng.latitude, mCurLatLng.longitude);
        } else if (v == binding.tvFindCarByMapSearch) {
            boolean canSearch = !TextUtils.isEmpty(getSearchText());
            if (!canSearch) {
                MToast.showToast(getContext(), "请先输入搜索内容");
                return;
            }
            isCameraToPosition = true;
            refreshData();
        } else if (v == binding.ivFindCarByMapSwitch) {
            //选中状态为地图模式，为选中状态为列表模式
            if (binding.ivFindCarByMapSwitch.isSelected()) {
                //列表模式
                mapShowing = false;
                binding.ivFindCarByMapSwitch.setSelected(false);
                Resources res = _mActivity.getResources();
                Drawable imgs = res.getDrawable(R.drawable.ditu_blue_black);
                imgs.setBounds(0, 0, imgs.getMinimumWidth(), imgs.getMinimumHeight());
                binding.ivFindCarByMapSwitch.setCompoundDrawables(imgs, null, null, null);
                binding.ivFindCarByMapSwitch.setText("图查");
                binding.srlFindCarByMapRefresh.setVisibility(View.VISIBLE);
                binding.listDataLayout.setVisibility(View.VISIBLE);
//                binding.flExpand.setVisibility(View.GONE);
            } else {
                //地图模式
                mapShowing = true;
                binding.ivFindCarByMapSwitch.setSelected(true);
                Resources res = _mActivity.getResources();
                Drawable imgs = res.getDrawable(R.drawable.liebiao_black);
                imgs.setBounds(0, 0, imgs.getMinimumWidth(), imgs.getMinimumHeight());
                binding.ivFindCarByMapSwitch.setCompoundDrawables(imgs, null, null, null);
                binding.ivFindCarByMapSwitch.setText("列表");
                binding.listDataLayout.setVisibility(View.GONE);
                binding.srlFindCarByMapRefresh.setVisibility(View.GONE);
//                binding.flExpand.setVisibility(View.VISIBLE);
            }
            refreshData();
        }
    }

    private void resetFilterData() {
        resetVehicleLocationData();
        resetCarTypeData();
        resetCarLen();
        resetTimeSelectData();
        resetFeatureData();
    }

    private void resetFeatureData() {
        mFeaturePop.resetSelectItem();
        mFilterAdapter.setTabStatusAndTitle(TAB_CAR_FEATURE, LogisticsFilterTabAdapter.NORMAL, "功能");
        viewModel.ldFilter.getValue().setCarFunction(new GoodsInfoTypeEntity3());
    }

    private void resetVehicleLocationData() {
        if (mSendPop != null) {
            viewModel.initAddress(getActivity(), viewModel.ldAddress.getValue());
        }
        //  viewModel.ldFilter.getValue().setSend(new GoodsSourceLocationEntity());
        //   resetMap();
    }

    private void resetMap() {
        mZoom = mMinZoom;
        mIsNeedLoadByCamera = false;
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(mCenterLatLng, mZoom));
    }

    private void resetCarTypeData() {
        if (mTypePop != null) {
            mTypePop.resetSelectItem();
        }
        viewModel.ldFilter.getValue().setCarType(null);
        binding.tlFindCarByMap.selectTab(binding.tlFindCarByMap.getTabAt(0));
    }

    private void resetCarLen() {
        if (mLenPop != null) {
            mLenPop.resetSelectItem();
        }
        viewModel.ldFilter.getValue().setCarLen(null);
        mFilterAdapter.setTabStatusAndTitle(TAB_CAR_LENGTH, LogisticsFilterTabAdapter.NORMAL, "车长");
    }

    private void resetTimeSelectData() {
        if (mLoadingTimePop != null) {
            mLoadingTimePop.resetDataNoCallBack();
        }
        viewModel.ldFilter.getValue().setShipmentTime(0);
        viewModel.ldFilter.getValue().setShipmentEndTime(0);
        mFilterAdapter.setTabStatus(TAB_CAR_DATE, LogisticsFilterTabAdapter.NORMAL);
    }

    private void resetSearchContent() {
        binding.etFindCarByMapSearch.setText("");
    }

    private String getSearchText() {
        return binding.etFindCarByMapSearch.getText().toString();
    }

    /**
     * 展示选择弹窗
     */
    public void showPopup(BasePopWindow pop) {
        pop.showPopwindow(binding.rvFindCarByMapFilter, 0, 0);
    }

    @Override
    public void onResume() {
        super.onResume();
        binding.mapFindCarByMap.onResume();
        clearMsgTip("");
    }

    @Override
    public void onPause() {
        super.onPause();
        binding.mapFindCarByMap.onPause();
    }

    @Override
    public void onSaveInstanceState(@NotNull Bundle outState) {
        super.onSaveInstanceState(outState);
        binding.mapFindCarByMap.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //注销im消息监听
//        NIMClient.getService(MsgServiceObserve.class).observeRecentContact(this, false);
        binding.mapFindCarByMap.onDestroy();
    }
}
